/**
 * 增强路径匹配功能演示脚本
 * 展示如何使用新的智能路径匹配功能
 */

import RequestManager from './request.js'
import { runPathMatchingTests, testSpecificPath } from './path-matching-tests.js'

/**
 * 演示基础路径匹配功能
 */
function demonstrateBasicMatching() {
  console.log('🎯 演示基础路径匹配功能')
  console.log('=' .repeat(50))
  
  const requestManager = new RequestManager()
  
  // 测试精确匹配
  console.log('\n1. 精确匹配测试:')
  testSpecificPath(requestManager, '/api/v1/user/profile', 'GET')
  testSpecificPath(requestManager, '/api/v1/habits/trending', 'GET')
  
  // 测试参数化匹配
  console.log('\n2. 参数化匹配测试:')
  testSpecificPath(requestManager, '/api/v1/users/123', 'GET')
  testSpecificPath(requestManager, '/api/v1/habits/456', 'PUT')
  
  // 测试嵌套资源
  console.log('\n3. 嵌套资源测试:')
  testSpecificPath(requestManager, '/api/v1/users/123/habits', 'GET')
  testSpecificPath(requestManager, '/api/v1/users/123/habits/456', 'GET')
  
  // 测试通配符匹配
  console.log('\n4. 通配符匹配测试:')
  testSpecificPath(requestManager, '/api/v1/files/document.pdf/download', 'GET')
  testSpecificPath(requestManager, '/api/v1/admin/system/logs', 'GET')
}

/**
 * 演示高级路径匹配功能
 */
function demonstrateAdvancedMatching() {
  console.log('\n🚀 演示高级路径匹配功能')
  console.log('=' .repeat(50))
  
  const requestManager = new RequestManager()
  
  // 测试参数类型验证
  console.log('\n1. 参数类型验证:')
  testSpecificPath(requestManager, '/api/v1/habits/789', 'GET') // 数字ID
  testSpecificPath(requestManager, '/api/v1/files/report.xlsx', 'GET') // 文件名格式
  
  // 测试版本化API
  console.log('\n2. 版本化API:')
  testSpecificPath(requestManager, '/api/v1/habits', 'GET')
  testSpecificPath(requestManager, '/api/v2/users/123', 'GET')
  
  // 测试通用资源操作
  console.log('\n3. 通用资源操作:')
  testSpecificPath(requestManager, '/api/v1/categories', 'GET')
  testSpecificPath(requestManager, '/api/v1/tags/123', 'PUT')
  testSpecificPath(requestManager, '/api/v1/comments', 'POST')
  
  // 测试多级通配符
  console.log('\n4. 多级通配符:')
  testSpecificPath(requestManager, '/api/v1/admin/system/error/logs', 'GET')
  testSpecificPath(requestManager, '/api/v1/cache/user/123/session/clear', 'DELETE')
}

/**
 * 演示查询参数处理
 */
function demonstrateQueryParams() {
  console.log('\n🔍 演示查询参数处理')
  console.log('=' .repeat(50))
  
  const requestManager = new RequestManager()
  
  // 测试带查询参数的路径
  const pathsWithQuery = [
    '/api/v1/habits?page=1&size=20',
    '/api/v1/users/123?include=profile,habits',
    '/api/v1/search/habits?q=运动&category=健康',
    '/api/v1/reports/monthly?year=2024&month=01&format=pdf'
  ]
  
  pathsWithQuery.forEach(path => {
    testSpecificPath(requestManager, path, 'GET')
  })
}

/**
 * 演示优先级匹配
 */
function demonstratePriorityMatching() {
  console.log('\n⚡ 演示优先级匹配')
  console.log('=' .repeat(50))
  
  const requestManager = new RequestManager()
  
  console.log('\n测试路径: /api/v1/habits/trending')
  console.log('应该匹配精确路径，而不是参数化路径 /api/v1/habits/:id')
  
  const result = testSpecificPath(requestManager, '/api/v1/habits/trending', 'GET')
  
  if (result && result.handler.method === 'getTrending') {
    console.log('✅ 优先级匹配正确：精确匹配优于参数匹配')
  } else {
    console.log('❌ 优先级匹配错误：应该匹配精确路径')
  }
}

/**
 * 演示错误处理
 */
function demonstrateErrorHandling() {
  console.log('\n🚫 演示错误处理')
  console.log('=' .repeat(50))
  
  const requestManager = new RequestManager()
  
  // 测试不存在的路径
  console.log('\n1. 测试不存在的路径:')
  testSpecificPath(requestManager, '/api/v1/unknown/endpoint', 'GET')
  
  // 测试方法不匹配
  console.log('\n2. 测试方法不匹配:')
  testSpecificPath(requestManager, '/api/v1/user/profile', 'POST')
  
  // 测试参数类型不匹配
  console.log('\n3. 测试参数类型验证:')
  testSpecificPath(requestManager, '/api/v1/habits/abc', 'GET') // 应该匹配通用资源路径
}

/**
 * 演示性能对比
 */
function demonstratePerformance() {
  console.log('\n📊 演示性能对比')
  console.log('=' .repeat(50))
  
  const requestManager = new RequestManager()
  
  // 测试路径列表
  const testPaths = [
    { path: '/api/v1/user/profile', method: 'GET' },
    { path: '/api/v1/users/123', method: 'GET' },
    { path: '/api/v1/users/123/habits/456', method: 'GET' },
    { path: '/api/v1/files/document.pdf/download', method: 'GET' },
    { path: '/api/v1/admin/system/logs', method: 'GET' },
    { path: '/api/v1/categories', method: 'GET' },
    { path: '/api/v1/tags/123', method: 'GET' }
  ]
  
  const iterations = 1000
  console.log(`\n执行 ${iterations} 次迭代，每次测试 ${testPaths.length} 个路径...`)
  
  const startTime = Date.now()
  
  for (let i = 0; i < iterations; i++) {
    for (const { path, method } of testPaths) {
      requestManager.findApiHandler(path, method)
    }
  }
  
  const endTime = Date.now()
  const totalTime = endTime - startTime
  const totalRequests = iterations * testPaths.length
  const avgTime = totalTime / totalRequests
  
  console.log(`\n性能测试结果:`)
  console.log(`  总时间: ${totalTime}ms`)
  console.log(`  总请求数: ${totalRequests}`)
  console.log(`  平均时间: ${avgTime.toFixed(3)}ms/请求`)
  console.log(`  吞吐量: ${(totalRequests / totalTime * 1000).toFixed(0)} 请求/秒`)
}

/**
 * 运行完整演示
 */
export function runCompleteDemo() {
  console.log('🎉 增强路径匹配功能完整演示')
  console.log('=' .repeat(60))
  
  try {
    // 基础功能演示
    demonstrateBasicMatching()
    
    // 高级功能演示
    demonstrateAdvancedMatching()
    
    // 查询参数演示
    demonstrateQueryParams()
    
    // 优先级匹配演示
    demonstratePriorityMatching()
    
    // 错误处理演示
    demonstrateErrorHandling()
    
    // 性能测试演示
    demonstratePerformance()
    
    console.log('\n🎯 演示完成！')
    console.log('\n💡 提示：')
    console.log('  - 可以使用 runPathMatchingTests() 运行完整测试套件')
    console.log('  - 可以使用 testSpecificPath() 测试特定路径')
    console.log('  - 查看 ENHANCED_PATH_MATCHING_GUIDE.md 获取详细使用指南')
    
  } catch (error) {
    console.error('❌ 演示过程中发生错误:', error)
  }
}

/**
 * 运行测试套件
 */
export function runTestSuite() {
  console.log('🧪 运行增强路径匹配测试套件')
  console.log('=' .repeat(60))
  
  const requestManager = new RequestManager()
  return runPathMatchingTests(requestManager)
}

/**
 * 快速验证功能
 */
export function quickValidation() {
  console.log('⚡ 快速功能验证')
  console.log('=' .repeat(30))
  
  const requestManager = new RequestManager()
  
  const quickTests = [
    { path: '/api/v1/user/profile', method: 'GET', desc: '精确匹配' },
    { path: '/api/v1/users/123', method: 'GET', desc: '参数匹配' },
    { path: '/api/v1/users/123/habits/456', method: 'GET', desc: '嵌套资源' },
    { path: '/api/v1/files/doc.pdf/download', method: 'GET', desc: '通配符' },
    { path: '/api/v1/categories', method: 'GET', desc: '通用资源' }
  ]
  
  let passed = 0
  let total = quickTests.length
  
  quickTests.forEach(({ path, method, desc }) => {
    try {
      const result = requestManager.findApiHandler(path, method)
      if (result) {
        console.log(`✅ ${desc}: ${path}`)
        passed++
      } else {
        console.log(`❌ ${desc}: ${path} - 未匹配`)
      }
    } catch (error) {
      console.log(`❌ ${desc}: ${path} - 错误: ${error.message}`)
    }
  })
  
  console.log(`\n📊 验证结果: ${passed}/${total} 通过 (${(passed/total*100).toFixed(1)}%)`)
  
  return { passed, total, success: passed === total }
}

// 如果直接运行此文件，执行快速验证
if (typeof window === 'undefined' && typeof global !== 'undefined') {
  // Node.js 环境
  quickValidation()
}

export default {
  runCompleteDemo,
  runTestSuite,
  quickValidation,
  demonstrateBasicMatching,
  demonstrateAdvancedMatching,
  demonstrateQueryParams,
  demonstratePriorityMatching,
  demonstrateErrorHandling,
  demonstratePerformance
}